from django.utils.safestring import mark_safe
from django.http.request import QueryDict


class Pagination:

    def __init__(self, page, all_count, params=None, per_num=10, max_show=9):
        if not params:
            params = QueryDict(mutable=True)
        self.params = params
        try:
            self.page = int(page)
            if self.page <= 0:
                self.page = 1
        except Exception:
            self.page = 1
        start = (self.page - 1) * per_num
        end = self.page * per_num
        self.start = start
        self.end = end
        page_count, more = divmod(all_count, per_num)
        if more:
            page_count += 1
        half_show = max_show // 2
        if page_count < max_show:
            page_start = 1
            page_end = page_count
        else:
            if self.page - half_show <= 0:
                page_start = 1
                page_end = max_show
            elif self.page + half_show > page_count:
                page_start = page_count - max_show + 1
                page_end = page_count
            else:
                page_start = self.page - half_show
                page_end = self.page + half_show
        self.page_count = page_count
        self.page_start = page_start
        self.page_end = page_end

    @property
    def page_html(self):
        page_list = []
        if self.page == 1:
            page_list.append(
                '<li class="disabled"><a aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>')
        else:
            self.params['page'] = self.page - 1
            page_list.append(
                '<li><a href="?{}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'.format(
                    self.params.urlencode()))
        for i in range(self.page_start, self.page_end + 1):
            self.params['page'] = i
            if i == self.page:
                page_list.append('<li class="active" ><a href="?{}">{}</a></li>'.format(self.params.urlencode(), i))
            else:
                page_list.append('<li><a href="?{}">{}</a></li>'.format(self.params.urlencode(), i))
        if self.page >= self.page_count:
            page_list.append(
                '<li class="disabled"><a aria-label="Previous"><span aria-hidden="true">&raquo;</span></a></li>')
        else:
            self.params['page'] = self.page + 1
            page_list.append(
                '<li><a href="?{}" aria-label="Previous"><span aria-hidden="true">&raquo;</span></a></li>'.format(
                    self.params.urlencode()))
        page_html = mark_safe(''.join(page_list))
        return page_html
